import AMapLoader from '@amap/amap-jsapi-loader'

export const initAMap = () => {
  window._AMapSecurityConfig = {
    securityJsCode: '3160b344be3ffde0af71bf32e3f7d55c'
  }
  const config = {
    key: '5f8ea60e809d2c7da845351e72efcb44', //设置您的key
    version: '2.0',
    plugin: ['AMap.Geolocation']
  }
  return new Promise((resolve, reject) => {
    AMapLoader.load(config)
      .then(AMap => {
        resolve(AMap)
      })
      .catch(error => {
        reject(error)
        console.log('error', error)
      })
  })
}

export const getGeolocation = () => {
  return new Promise((resolve, reject) => {
    initAMap()
      .then((AMap: any) => {
        AMap.plugin('AMap.Geolocation', function () {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
            timeout: 1000, // 设置定位超时时间，默认：无穷大
            buttonPosition: 'RB',
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true,
            needAddress: true
          })
          resolve(geolocation)
        })
      })
      .catch(error => {
        reject(error)
        console.log('error', error)
      })
  })
}

// 优先获取定位信息,定位信息获取不到使用城市信息
export const getAMapPosition = () => {
  return new Promise((reslove, reject) => {
    getGeolocation().then((geolocation: any) => {
      geolocation?.getCurrentPosition((status, result) => {
        if (status == 'complete') {
          // result为对应的地理位置详细信息
          reslove(result.formattedAddress)
        } else {
          geolocation.getCityInfo((status, result) => {
            if (status == 'complete') {
              // result为对应的地理位置详细信息
              reslove(result.city)
            } else {
              reject(result.message)
            }
          })
        }
      })
    })
  })
}
